package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /*
    * 处理超时订单的方法
    * */
    //@Scheduled(cron = "0 * * * * ?") //每分钟执行一次
//    @Scheduled(cron = "0/3 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理超时订单,{}",LocalDateTime.now());
        //当前时间减去15分钟即为超时订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //根据状态和订单时间查询所有超时订单
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        //遍历超时订单列表
        for (Orders orders : ordersList) {
            //设置订单状态为已取消
            orders.setStatus(Orders.CANCELLED);
            //设置取消原因
            orders.setCancelReason("订单超时，自动取消！");
            //设置取消时间
            orders.setCancelTime(LocalDateTime.now());
            //更新订单
            ordersMapper.update(orders);
        }
    }
    /*
    * 处理一直处于派送中状态的订单
    * */
    //@Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行一次
//    @Scheduled(cron = "0/3 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中的订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //根据状态和订单时间查询所有超时订单
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        //遍历超时订单列表
        for (Orders orders : ordersList) {
            //设置订单状态为已完成
            orders.setStatus(Orders.COMPLETED);
            //更新订单
            ordersMapper.update(orders);
        }
    }
}
